import datetime
import sys

class ChatRoom(object):
    """A chatroom"""

    rooms = {}

    def __init__ (self, name):
        self.name = name
        self.users = []
        self.message = []
        ChatRoom.rooms[name] = self

    def addSubscriber(self, subscriber):
        self.users.append(subscriber)
        subscriber.sendMessage(self.name, "User %s has entered." % subscriber.username)

    def removeSubscriber(self, subscriber):
        if subscriber in self.users:
            subscriber.sendMesaage(self.name, "User %s is leaving." % subscriber.username)
            self.users.remove(subscriber)

    def addMessage(self, msg):
        self.message.append(msg)

    def printMessage(self, out):
        print ("Chat Transcript for: %s" % self.name)
        for i in self.message:
            print >> out, i
########## end of class CharRoom ################

class ChatUser(object):
    """A user participating in chats"""
    def __init__(self, username):
        self.username = username
        self.rooms = {}

    def subscribe(self, roomname):
        if roomname in ChatRoom.rooms:
            room = ChatRoom.rooms[roomname]
            self.rooms[roomname] = room
            room.addSubscriber(self)
        else:
            raise ChatError("No such room %s" % roomname)

    def sendMessage(self, roomname, text):
        if roomname in  self.rooms:
            room = self.rooms[roomname]
            cm = ChatMessage(self, text)
            room.addMessage(cm)
        else:
            raise ChatError("User %s not subscribed to chat %s" % (self.username, roomname))

    def displayChat(self, roomname, out):
        if roomname in self.rooms:
            room = self.rooms[roomname]
            room.printMessage(out)
        else:
            raise ChatError("User %s not subscribed to chat %s" % (self.username, roomname))

#########################################################
class ChatMessage(object):
    """A single sent by a user to a chatroom"""
    def __init__(self, user, text):
        self.sender = user
        self.msg = text
        self.time = (datetime.datetime.now())
		#self.time = time.strftime("%H:%M:%S")

    def __str__(self):
        return "From: %s at %s: %s" % (self.sender.username, self.time, self.msg)
        return "From: %s: %s" % (self.sender.username, self.msg)

#########################################################
def main():
    room = ChatRoom("Wayne's apartment")
    markcc = ChatUser("MarkCC")
    markcc.subscribe("Wayne's apartment")
    parg = ChatUser("Parg")
    parg.subscribe("Wayne's apartment")

    markcc.sendMessage("Wayne's apartment", "Hello, is there anybody alive ?")
    parg.sendMessage("Wayne's apartment", "Yesh, I'm here, man.")
    markcc.displayChat("Wayne's apartment", sys.stdout)

if __name__ == "__main__":
    main()

############### End of File ###################
